/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.scalia.meteocal.gui;

import com.scalia.meteocal.control.NotificationManager;
import com.scalia.meteocal.entity.Notification;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.component.commandbutton.CommandButton;
import org.primefaces.context.RequestContext;
/**
 *
 * @author gabriele
 */
@ManagedBean
@ViewScoped
public class NotificationBean implements Serializable {
    
    private static final String NOT_READ_STYLE = "not_read";
    private static final String BOLD = "bold";
    private static final String NOTIFICATION_BUTTON_ID = "barform:notificationButton";
    private static final String FORM_ID = "barform";
    
    @EJB
    private NotificationManager notificationManager;
     
    private List<Notification> currentNotifications;
    
    @PostConstruct
    public void init() {
        currentNotifications = notificationManager.getAllMyNotificationsNewFirst();
    }
    
    
    public List<Notification> getNotifications() { 
        return currentNotifications;
    }
    
    public void updateNotifications() {
        List<Notification> newCurrentNotifications = notificationManager.getAllMyNotificationsNewFirst();
        if (currentNotifications.size() < newCurrentNotifications.size()) {
            currentNotifications = newCurrentNotifications;
            RequestContext.getCurrentInstance().update(FORM_ID);
        }
    }
    
    public String getNotificationStyle() {       
        FacesContext context = FacesContext.getCurrentInstance();
        Notification notification = context.getApplication().evaluateExpressionGet(context, "#{notification}", Notification.class);
        
        return notification.getRead() ? new String() : NOT_READ_STYLE;
    }
    
    public String getNotificationsNotRead() {
        int notificationsNotRead = 0;
        for (Notification notification : currentNotifications) {
            if (!notification.getRead()) {
                notificationsNotRead++;
            }
        }
        return notificationsNotRead == 0 ? "" : "(" + String.valueOf(notificationsNotRead) + ")";
    }
    
    public void notificationButtonClicked() {
        for (Notification notification : currentNotifications) {
            if (!notification.getRead()) {
                notificationManager.readNotification(notification);
            }
        }
        RequestContext.getCurrentInstance().update(NOTIFICATION_BUTTON_ID);
    }
    
}
